package com.changgou.business.listener;

import okhttp3.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Map;

/**
 * @Author Tang
 * @Date 2020/9/15 20:05
 * @Description
 */
@Component
public class AdListener {

    //远程调用模板对象
    @Autowired
    private RestTemplate restTemplate;

    /*该注解指定目标方法来作为消费消息的方法，
        通过注解参数指定所监听的队列或者Binding
     */
    @RabbitListener(queues = {"ad_update_queue"})
    public void receiveMessage(String message) {
        System.out.println("接收到的消息为:" + message);

        //okHttpClient发起远程调用
       /*
        OkHttpClient okHttpClient = new OkHttpClient();
        String url = "http://192.168.200.128/ad_update?position="+message;
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功
                System.out.println("请求成功:"+response.message());
            }
        });*/

        //restTemplate远程访问地址
        String url = "http://192.168.200.128/ad_update?position=" + message;
        //发起远程调用,map={"flag":true,"position":"web_index_lb"}
        Map map = restTemplate.getForObject(url, Map.class);
        if (map != null) {
            //请求成功
            System.out.println("请求成功:" + map);

        } else {
            System.out.println("请求失败");
        }


    }
}
